package com.mayo.series;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

import com.mayo.series.comun.BaseActivity;
import com.mayo.series.comun.ComunUtilidades;
import com.mayo.series.json.objects.SerieObject;
import com.tjerkw.slideexpandable.library.SlideExpandableListAdapter;

public class RecomendacionSeriesActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_listado_mis_series);
		
		actionBar.setTitle(R.string.tit_recomendacion_series);
		actionBar.setSubtitle(R.string.tit_subtit_recomendacion);
		
		listaMisSeries = (ListView) findViewById(R.id.listado_series);
		
		new LoadSeriesRecomendadas().execute();
		
	  }
	
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	
    /**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	public class LoadSeriesRecomendadas extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(RecomendacionSeriesActivity.this);
			pDialog.setMessage("Cargando el listado de series.");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			String error = "0";
			List<NameValuePair> params;
			JSONObject json = new JSONObject();
			try {
				params = new ArrayList<NameValuePair>();
//				params.add(new BasicNameValuePair("comunidad", args[0]));
				json = jParser.makeHttpRequest(ComunUtilidades.URL_GET_SERIES_RECOMENDADAS, "GET", params);
				Log.d("Series recomendadas: ", json.toString());
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					series = json.getJSONArray(TAG_SERIES);
					adapter = new ListAdapter(series.length(), getApplicationContext());

					// looping through All Products
					for (int i = 0; i < series.length(); i++) {
						JSONObject c = series.getJSONObject(i);
						
						int id = c.getInt(TAG_ID);
						String name = c.getString(TAG_NOMBRE);
						String desc = c.getString(TAG_DESCRIPCION);
						String pais = c.getString(TAG_PAIS);
						String fecha = c.getString(TAG_FECHA_ESTRENO);
						String fechaFin = c.getString(TAG_FECHA_FIN);
						String imagen = ComunUtilidades.SERVIDOR_IMAGENES + c.getString(TAG_IMAGEN);
						int dia = c.getInt(TAG_DIA_EMISION);
						String estado = c.getString(TAG_ESTADO);
						String temp = c.getString(TAG_TEMPORADA);
						String capi = c.getString(TAG_NUM_CAPITULOS);
						String valoracion = c.getString(TAG_VALORACION);
						
						SerieObject agr = new SerieObject(id, name, desc, pais, fecha, fechaFin, imagen, dia, estado, temp, capi, valoracion);
						adapter.addItem(agr);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
				error = "1";
			} catch (RuntimeException e) {
				e.printStackTrace();
				error = "1";
			}

			return error;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(final String error) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
			 public void run() {
				if (error.equals("0")) {
//					listaAgrupaciones.setAdapter(adapter);
					listaMisSeries.setAdapter(
				            new SlideExpandableListAdapter(
				                adapter,
				                R.id.expandable_toggle_button,
				                R.id.expandable
				            )
				            );
					adapter.setFavorites();
				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.error_conexion),
							Toast.LENGTH_LONG).show();
				}
			 }
			});

		}
	}
	
}
